<template>
  <div class="track-page">
    <div class="track-table">
      <Table
        ref="tableRef"
        :columns="tableColumns"
        :options="{
          headerFixed: true,
          minWidth: 120,
          setting: { show: true, storage: true, storageKey: 'track-table' },
          searchSetting: { show: true, storage: true, storageKey: 'track-table_search', title: '问题', isFilter: false }
          // virtual: { type: 'fix', options: { height: 138, bufferNumber: 2, offsetTop: 45 } }
        }"
        :api="getProjectProblemPage"
        :after-api-transform-data="afterApiTransformData"
        :pagination="pagination"
      >
        <template #tool-right>
          <el-button type="primary" v-auth="'add'" class="mr30" :icon="Plus" @click="openDialog">新增</el-button>
        </template>
        <template #projectId="{ scope }">
          <AuthTable :permissions="authStore.authButtonList" :key-string="Component_Name">
            <template #edit>
              <TriggerContext
                class="trigger-context-status"
                :component="People"
                :props="{
                  id: scope.projectId,
                  list: projectList,
                  handleDateChange: (date: any) => {
                    editHandler({
                      id: scope.id,
                      tableName: TABLE_NAME,
                      fieldName: 'projectId',
                      newValue: date
                    });
                  }
                }"
              >
                <div class="wik-column-rl">
                  <div class="track-table-name">
                    {{ scope.projectCode }}
                  </div>
                  <el-icon><ArrowDown /></el-icon>
                </div>
              </TriggerContext>
            </template>
            <template #get>
              <div class="track-table-status">
                {{ scope.projectCode }}
              </div>
            </template>
          </AuthTable>
        </template>
        <template #projectName="{ scope }">
          <div class="track-table-status sle">
            {{ scope.projectName }}
          </div>
        </template>
        <template #productCategoryId="{ scope }">
          <AuthTable :permissions="authStore.authButtonList" :key-string="Component_Name">
            <template #edit>
              <TriggerContext
                class="trigger-context-status"
                :component="People"
                :props="{
                  id: scope.productCategoryId,
                  list: agvTypeList,
                  handleDateChange: (date: any) => {
                    editHandler({
                      id: scope.id,
                      tableName: TABLE_NAME,
                      fieldName: 'productCategoryId',
                      newValue: date
                    });
                  }
                }"
              >
                <div class="wik-column-rl">
                  <div class="track-table-status">
                    {{ agvTypeList.find((item: any) => item.id == scope.productCategoryId)?.name }}
                  </div>
                  <el-icon><ArrowDown /></el-icon>
                </div>
              </TriggerContext>
            </template>
            <template #get>
              <div class="track-table-status">
                {{ agvTypeList.find((item: any) => item.id == scope.productCategoryId)?.name }}
              </div>
            </template>
          </AuthTable>
        </template>
        <template #[item]="{ scope }" v-for="item in inputTemplateList" :key="item">
          <AuthTable :permissions="authStore.authButtonList" :key-string="Component_Name">
            <template #edit>
              <TextArea
                :value="scope[item]"
                @change="(val: any) => editHandler({ id: scope.id, tableName: TABLE_NAME, fieldName: item, newValue: val || '' })"
              />
            </template>
            <template #get>
              <span class="track-table-text sle">{{ scope[item] }}</span>
            </template>
          </AuthTable>
        </template>
        <template #status="{ scope }">
          <AuthTable :permissions="authStore.authButtonList" :key-string="Component_Name">
            <template #edit>
              <TriggerContext
                class="trigger-context-status"
                :component="Status"
                :props="{
                  id: scope.status,
                  list: dealOrderStatus(getDict('projectProblemStatus')),
                  handleDateChange: (date: any) => {
                    editHandler({
                      id: scope.id,
                      tableName: TABLE_NAME,
                      fieldName: 'status',
                      newValue: date
                    });
                  }
                }"
              >
                <div class="wik-column-rl">
                  <div class="track-table-status" :class="colorOrderStatusMap[scope.status]">
                    {{ getDictItem("projectProblemStatus", scope.status) }}
                  </div>
                  <el-icon><ArrowDown /></el-icon>
                </div>
              </TriggerContext>
            </template>
            <template #get>
              <div v-show="scope.status" class="track-table-status" :class="colorOrderStatusMap[scope.status]">
                {{ getDictItem("projectProblemStatus", scope.status) }}
              </div>
            </template>
          </AuthTable>
        </template>
        <template #typeId="{ scope }">
          <AuthTable :permissions="authStore.authButtonList" :key-string="Component_Name">
            <template #edit>
              <TriggerContext
                class="trigger-context-status"
                :component="Status"
                :props="{
                  id: scope.typeId,
                  list: dealOrderStage(getDict('projectProblemType')),
                  handleDateChange: (date: any) => {
                    editHandler({
                      id: scope.id,
                      tableName: TABLE_NAME,
                      fieldName: 'typeId',
                      newValue: date
                    });
                  }
                }"
              >
                <div class="wik-column-rl">
                  <div class="track-table-status" :class="colorOrderStageMap[scope.typeId]">
                    {{ getDictItem("projectProblemType", scope.typeId) }}
                  </div>
                  <el-icon><ArrowDown /></el-icon>
                </div>
              </TriggerContext>
            </template>
            <template #get>
              <div v-show="scope.typeId" class="track-table-status" :class="colorOrderStageMap[scope.typeId]">
                {{ getDictItem("projectProblemType", scope.typeId) }}
              </div>
            </template>
          </AuthTable>
        </template>
        <template #[item]="{ scope }" v-for="item in userColumns" :key="item">
          <div class="wik-column">
            <AuthTable :permissions="authStore.authButtonList" :key-string="Component_Name">
              <template #edit>
                <TriggerContext
                  class="trigger-context-status wik-column-item"
                  :component="People"
                  :props="{
                    id: scope[item],
                    list: userList,
                    handleDateChange: (date: any) => {
                      editHandler({
                        id: scope.id,
                        tableName: TABLE_NAME,
                        fieldName: item,
                        newValueId: date,
                        newValue: userList.find((itm: any) => itm.id === date)?.name
                      });
                    }
                  }"
                >
                  <div class="wik-column-rl">
                    <span class="order-table-name">{{ userList.find((itm: any) => itm.id === scope[item])?.name }}</span>
                    <el-icon><User /></el-icon>
                  </div>
                </TriggerContext>
              </template>
              <template #get>
                <span class="order-table-text wik-column-item">{{
                  userList.find((itm: any) => itm.id === scope[item])?.name
                }}</span>
              </template>
            </AuthTable>
          </div>
        </template>
        <template #[item]="{ scope }" v-for="item in timeColumnTemplateList" :key="item">
          <AuthTable :permissions="authStore.authButtonList" :key-string="Component_Name">
            <template #edit>
              <TriggerContext
                :component="Calendar"
                :props="{
                  'selected-Date': scope[item],
                  handleDateChange: async (date: any) => {
                    editHandler({
                      id: scope.id,
                      tableName: TABLE_NAME,
                      fieldName: item,
                      newValue: date
                    });
                  }
                }"
              >
                <div class="wik-column-rl">
                  <span class="order-table-name">{{ formatHandler(scope[item]) }}</span>
                  <svg-icon name="rl"></svg-icon>
                </div>
              </TriggerContext>
            </template>
            <template #get>
              <span class="order-table-text">{{ formatHandler(scope[item]) }}</span>
            </template>
          </AuthTable>
        </template>
        <template #problemPartId="{ scope }">
          <AuthTable :permissions="authStore.authButtonList" :key-string="Component_Name">
            <template #edit>
              <TriggerContext
                class="trigger-context-status"
                :component="Status"
                :props="{
                  id: scope['problemPartId'],
                  list: dealDic(getDict('projectProblemPosition')),
                  handleDateChange: async (date: any) => {
                    editHandler({
                      id: scope.id,
                      tableName: TABLE_NAME,
                      fieldName: 'problemPartId',
                      newValue: date
                    });
                  }
                }"
              >
                <div class="wik-column-rl">
                  <div class="order-table-status">
                    {{ getDictItem("projectProblemPosition", scope["problemPartId"]) }}
                  </div>
                  <el-icon><ArrowDown /></el-icon>
                </div>
              </TriggerContext>
            </template>
            <template #get>
              <span class="order-table-text">{{ getDictItem("projectProblemPosition", scope["problemPartId"]) }}</span>
            </template>
          </AuthTable>
        </template>
        <template #problemStageId="{ scope }">
          <AuthTable :permissions="authStore.authButtonList" :key-string="Component_Name">
            <template #edit>
              <TriggerContext
                class="trigger-context-status"
                :component="Status"
                :props="{
                  id: scope['problemStageId'],
                  list: dealDic(getDict('projectProblemStage')),
                  handleDateChange: async (date: any) => {
                    editHandler({
                      id: scope.id,
                      tableName: TABLE_NAME,
                      fieldName: 'problemStageId',
                      newValue: date
                    });
                  }
                }"
              >
                <div class="wik-column-rl">
                  <div class="order-table-status">
                    {{ getDictItem("projectProblemStage", scope["problemStageId"]) }}
                  </div>
                  <el-icon><ArrowDown /></el-icon>
                </div>
              </TriggerContext>
            </template>
            <template #get>
              <span class="order-table-text">{{ getDictItem("projectProblemStage", scope["problemStageId"]) }}</span>
            </template>
          </AuthTable>
        </template>
        <template #projectProblemImgList="{ scope }">
          <AuthTable :permissions="authStore.authButtonList" :key-string="Component_Name">
            <template #edit>
              <Image :url-list="scope.projectProblemImgList" :problem-id="scope.id" @change="tableRef.refresh()" />
            </template>
          </AuthTable>
        </template>
        <template #options="{ scope }">
          <el-button type="text" @click="() => deleteQuestion(scope)" v-auth="'delete'">删除</el-button>
        </template>
      </Table>
    </div>
  </div>
</template>
<script lang="ts" setup>
import dayjs from "dayjs";
import { ArrowDown, Plus } from "@element-plus/icons-vue";
import { ref, onMounted } from "vue";
import Table from "@/components/Table/index.vue";
import { getProjectListCodeAll } from "@/api/modules/project";
import { getProjectProblemPage, updateProjectProblemUpdateByField, deleteProjectProblem } from "@/api/modules/project"; // deleteProjectProblem, updateProjectProblem
import { useHandleData } from "@/hooks/useHandleData";
import { getProductModelList } from "@/api/modules/carType";
import TriggerContext from "@/components/TriggerContext/index.vue";
import AuthTable from "@/components/AuthTable/index.vue";
import { People, TextArea, Status, Calendar, Image } from "./components/index";
import { COLUMNS, TABLE_NAME, Component_Name } from "./constant";
import { getListAllUser } from "@/api/modules/sys";
import { useAdd } from "./hooks/useAdd";
import { useAuthStore } from "@/stores/modules/auth";
import { useDict } from "@/hooks/useDict";
const authStore = useAuthStore();
const { getDictItem, getDict } = useDict([
  "projectProblemStatus",
  "projectProblemType",
  "projectProblemPosition",
  "projectProblemStage"
]);

const tableRef = ref<any>(null);
let projectList = ref<any>([]);
let agvTypeList = ref<any>([]);
let userList = ref<any>([]);

const pagination = ref({
  pageSize: 20,
  currentPage: 1,
  total: 0
});

const tableColumns = ref(COLUMNS);

const { openDialog } = useAdd({ tableRef });

const afterApiTransformData = (data: any) => {
  return data;
};

// input模板字段列表
const inputTemplateList = ref([
  "content",
  "problemReason",
  "problemFollow",
  "productCategoryName",
  "replyContent",
  "problemSite"
]);

// 用户内容列
const userColumns = ref<any>(["userId", "problemUserId", "replyUserId"]);

// 时间内容列
const timeColumnTemplateList = ref<any>(["planCompleteTime", "completeTime", "gmtCreate"]);

// 处理进度状态
const colorOrderStatus = [
  "track-table-status-progress1",
  "track-table-status-progress2",
  "track-table-status-progress3",
  "track-table-status-progress4",
  "track-table-status-progress5"
];
const colorOrderStatusMap: any = {};
const dealOrderStatus = (list: any) => {
  return (
    (list &&
      list.map((item: any, index: number) => {
        item.className = colorOrderStatus[index];
        colorOrderStatusMap[item.id] = item.className;
        return item;
      })) ||
    []
  );
};
const formatHandler = (val: any) => {
  return val ? dayjs(val).format("YYYY年MM月DD日") : "--";
};
// 处理阶段
const colorOrderStage = [
  "track-table-status-type1",
  "track-table-status-type2",
  "track-table-status-type3",
  "track-table-status-type4"
];
const colorOrderStageMap: any = {};
const dealOrderStage = (list: any) => {
  return (
    (list &&
      list.map((item: any, index: number) => {
        item.className = colorOrderStage[index];
        colorOrderStageMap[item.id] = item.className;
        return item;
      })) ||
    []
  );
};

// 处理字典
const dealDic = (list: any) => {
  return (
    (list &&
      list.map((item: any) => {
        item.colorText = "#666";
        return item;
      })) ||
    []
  );
};

// 编辑订单
const editHandler = async (params: any) => {
  await updateProjectProblemUpdateByField(params);
  tableRef.value.refresh();
};

// 获取所有项目
const getProject = async () => {
  const { data } = await getProjectListCodeAll();
  projectList.value =
    (data &&
      data.map((item: any) => {
        item.nameClone = item.code + "-" + item.name;
        return item;
      })) ||
    [];
};
//  获取所有车型
const getCarType = async () => {
  const { data } = await getProductModelList();
  agvTypeList.value = data || [];
};
// 获取所有用户
const getListAllUserApi = async () => {
  const { data } = await getListAllUser();
  userList.value = data || [];
};

// 删除回答信息
const deleteQuestion = async (params: any) => {
  await useHandleData(deleteProjectProblem, { id: params.id }, `删除问题`);
  tableRef.value.refresh();
};

onMounted(() => {
  getProject();
  getCarType();
  getListAllUserApi();
});
</script>
<style lang="scss" scoped>
.track-page {
  height: 100%;
  display: flex;
  flex-flow: column nowrap;
  gap: 20px;
  .track-table {
    width: 100%;
    height: 100%;
  }
  :deep(.wik-table-feature) {
    .wik-tools {
      flex: 0 0 72px;
      margin-bottom: 10px;
      background: #ffffff;
      .wik-tools-left-search {
        border: 1px solid #dddfe6;
        box-sizing: border-box;
        height: 32px;
        .el-icon {
          height: inherit;
        }
        .el-input__wrapper {
          box-sizing: border-box;
        }
        .el-input__inner {
          height: 28px;
          line-height: 28px;
        }
      }
    }
    .wik-table {
      background: #ffffff;
    }
    .wik-pagination {
      margin-top: 10px;
      background: #ffffff;
    }
  }
  .wik-column {
    width: 100%;
    overflow: hidden;
    .wik-column-item {
      display: block;
      align-items: center;
      height: 45px;
      padding: 0 10px;
      overflow: hidden;
      line-height: 45px;
      text-overflow: ellipsis;
      white-space: nowrap;
      box-sizing: border-box;
      cursor: default;
      border-bottom: 1px solid #eeeeee;
      &:last-child {
        border: 0;
      }
      &:hover {
        background: var(--el-color-primary-light-9);
      }
    }
  }
  .wik-column-client {
    display: flex;
    flex-flow: flex-start nowrap;
    align-items: center;
    gap: 8px;
    padding: 0 10px;
    width: 100%;
    overflow: hidden;
    .el-icon {
      color: $primary-color;
    }
  }
  .wik-column-rl {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: inherit;
    padding: 6px 10px;
    cursor: pointer;
    .track-table-status {
      flex: 1;
    }
    .track-table-input {
      height: 100%;
      margin-right: 10px;
      margin-left: 0;
    }
    svg {
      display: none;
      color: #aaaaaa;
      flex: 0 0 14px;
    }
    &:hover {
      svg {
        display: block;
      }
    }
    :deep(.el-input) {
      height: 100%;
      .el-input__wrapper {
        box-shadow: none;
      }
    }
  }
  .trigger-context {
    width: inherit;
    height: inherit;
  }
  .trigger-context-status {
    display: grid;
    align-items: center;
    width: 100%;
    height: inherit;
    cursor: pointer;
  }
  .track-table-status {
    height: 22px;
    border-radius: 14px;
    border: 1px solid transparent;
    margin: 0 16px;
    font-size: 14px;
    line-height: 22px;
    text-align: center;
  }
  .track-table-status-delay {
    height: 22px;
    border-radius: 14px;
    border: 1px solid #c8cee0;
    margin: 0 16px;
    font-size: 12px;
    line-height: 22px;
    text-align: center;
    color: #c8cee0;
    width: 100%;
  }
  .track-table-status-delay_active {
    border: 1px solid #f65353;
    color: #f65353;
  }
  .track-table-head {
    margin: 0 16px;
  }
  .track-table-text {
    margin: 0 16px;
  }
  .track-table-document {
    color: $primary-color;
  }
}
</style>

<style lang="scss">
.track-table-status-progress1 {
  color: $order-color-2;
  background-color: $order-bg-color-2;
}
.track-table-status-progress2 {
  color: $order-color-1;
  background-color: $order-bg-color-1;
}
.track-table-status-progress3 {
  color: $order-color-3;
  background-color: $order-bg-color-3;
}
.track-table-status-progress4 {
  color: $order-color-5;
  background-color: $order-bg-color-5;
}
.track-table-status-progress5 {
  color: $order-color-4;
  background-color: $order-bg-color-4;
}

.track-table-status-type1 {
  color: $order-color-3;
  background-color: $order-bg-color-3;
}
.track-table-status-type2 {
  color: $order-color-1;
  background-color: $order-bg-color-1;
}
.track-table-status-type3 {
  color: $order-color-2;
  background-color: $order-bg-color-2;
}
.track-table-status-type4 {
  color: $order-color-4;
  background-color: $order-bg-color-4;
}
</style>
